// 表示状态实体。
// IType: 转换的类型。
export class State<IType> {
  name:string = '';
  onEnter?: (type: IType) => boolean;
  onEntered?: (type: IType) => void; 
  onExited?: (type: IType) => void;
  transitions:Array<Transition<IType>> = [];
  constructor(name:string=''){
    this.name = name;
  }
  // 添加转换状态。从type状态转换到state
  addTransition(type:IType, state:State<IType>){
    this.transitions.push(new Transition(type,state));
  }
  // 执行转换
  doTransition(type:IType){
    const transition = this.transitions.find(t => t.type === type);
    if(!transition){ 
      //console.log(`状态转换失败，未找到${this.name}-${type}的转换状态`);
      return null;
    }
    const nextState = transition.state;
    const canEnter = nextState.onEnter?.(type);
    if(!canEnter && nextState.onEnter) {
      return null;
    } 
    this.onExited?.(type);
    nextState.onEntered?.(type);
    return transition.state; 
  }
}
// 绑定转换和状态的类
 class Transition<IType> {
  type: IType;
  state:State<IType>;
  constructor(type:IType,state:State<IType>){
    this.type = type;
    this.state = state;
  }
}
/**
 * 状态机上下文。
 */
export class Context<IType> {
  currentState:State<IType> | null = null;
  initState(state:State<IType>){
    this.currentState = state;
  } 
  doTransition(type:IType){
    const nextState = this.currentState?.doTransition(type);
    if(nextState){
        this.currentState = nextState;
        return true;
   }
   return false;
  }
}